package rpc.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MethodProxy implements InvocationHandler {
    
    /**
     * 被代理对象 可能为null
     */
    private Object obj;
    
    public MethodProxy(Object newInstance) {
        this.obj = newInstance;
    }
    
    public MethodProxy() {
        super();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> methodClass = method.getDeclaringClass();
        if(methodClass.isInterface() && obj == null){
            System.out.println("执行接口的方法");
            return run(method, args);
        } else {
            if(obj == null){
                throw new RuntimeException("未初始化代理对象");
            }
            System.out.println("执行具体实现类的方法");
            return method.invoke(obj, args);
        }
    }

    public Object run(Method method, Object[] args) {
        // 如果是执行接口的方法，则此方法才是方法的真正动态实现
        //RPC调用---client端
        String interfaceName = method.getDeclaringClass().toString();
        //序列化参数
        System.out.println(interfaceName);
        System.out.println("run over");
        return "method call success";
    }

}
